package com.sdr.tackvideo.tackvideo;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sdr.tackvideo.R;
import com.sdr.tackvideo.base.BaseActivity;
import com.sdr.tackvideo.view.RecordedButton;

import java.io.File;

public class TackVideoActivity extends BaseActivity implements TackVideo.RecorderListener {
    public static final String TYPE = "type";
    public static final String PREVIEW_PATH = "videopath";
    public static final String SAVE_PATH = "savepath";

    public static final String RESULT = "reslut";

    public static final int PREVIEW_VIDEO = 0x000000;
    public static final int TACK_VIDEO = 0x000001;
    public static final int TACK_PHOTO = 0x000010;

    private int enterType = -1;
    // 预览视频的地址
    private String previePath;
    //存储视频/照片的地址
    private String savePath;

    private SurfaceView svPreView, svTackVideo;
//    private ImageView prePhoto;
    private FrameLayout flPreView, flTackVideo;
    private TextView tvCaption;
    private ImageView ivFinish, ivDelete, ivConfirm;
    private RecordedButton btnRecord;
    private Toolbar mToolbar;

    private TackVideo tackVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 锁定竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_tack_video);
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        if (tackVideo != null) {
            btnRecord.setMax(tackVideo.getMaxTime());
            btnRecord.setOnGestureListener(new RecordedButton.OnGestureListener() {
                @Override
                public void onLongClick() {
                    if (enterType == TACK_VIDEO) {
                        tvCaption.setText("松开保存");
                        tackVideo.startRecord();
                    }
                }

                @Override
                public void onClick() {
                    if (enterType == TACK_PHOTO) {
                        tackVideo.tackPhoto();
                    }
                }

                @Override
                public void onLift() {
                    if (enterType == TACK_VIDEO) {
                        tvCaption.setText("长按拍摄");
                        tackVideo.stopRecordSave(tackVideo.getOutputFile());
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                btnRecord.setProgress(0);
                            }
                        }, 300);
                    }
                }

                @Override
                public void onOver() {
                    if (enterType == TACK_VIDEO) {
                        tackVideo.stopRecordSave(tackVideo.getOutputFile());
                        btnRecord.setProgress(0);
                        btnRecord.closeButton();
                        tvCaption.setText("长按拍摄");
                    }
                }
            });
        }

        ivFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                //执行关闭动画
                closeActivityAnim();
            }
        });

        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchOperation(flTackVideo, flPreView);
                if (enterType == TACK_VIDEO) {
                    // 切换回去
                    svTackVideo.setVisibility(View.VISIBLE);
                    svPreView.setVisibility(View.GONE);
                    //删除掉原来的文件
                    File file = tackVideo.getOutputFile();
                    if (file.exists()) file.delete();
                }else if (enterType == TACK_PHOTO){
                    //删除掉原来拍摄的图片
                    File photoFile = tackVideo.getPhotoFile();
                    if (photoFile.exists())photoFile.delete();
                    // 重新预览
                    tackVideo.startPreView();
                    // 切换回去
//                    svTackVideo.setVisibility(View.VISIBLE);
//                    prePhoto.setVisibility(View.GONE);
                }
            }
        });


        ivConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (enterType == TACK_VIDEO) {
                    File file = tackVideo.getOutputFile();
                    if (file.exists()) {
                        Intent intent = new Intent();
                        intent.putExtra(RESULT, file.getAbsolutePath());
                        setResult(RESULT_OK, intent);
                        //刷新媒体库
                        TackVideoUtil.updataMedia(TackVideoActivity.this,file);
                        finish();
                        //执行关闭动画
                        closeActivityAnim();
                    }
                }else if (enterType == TACK_PHOTO){
                    File photoFile = tackVideo.getPhotoFile();
                    if (photoFile!=null && photoFile.exists()){
                        Intent intent = new Intent();
                        intent.putExtra(RESULT, photoFile.getAbsolutePath());
                        setResult(RESULT_OK, intent);
                        //刷新媒体库
                        TackVideoUtil.updataMedia(TackVideoActivity.this,photoFile);
                        finish();
                        //执行关闭动画
                        closeActivityAnim();
                    }
                }
            }
        });
    }

    private void initData() {
        if (enterType == PREVIEW_VIDEO) {
            PreView preView = new PreView(this, svPreView);
            preView.setVideoPath(previePath);
            preView.init();
            Drawable drawable = getResources().getDrawable(R.drawable.ic_arrow_back);
            drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
            mToolbar.setNavigationIcon(drawable);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        } else if (enterType == TACK_VIDEO) {
            tackVideo = new TackVideo(this, svTackVideo);
            tackVideo.maxTime(15000);
            tackVideo.savePath(savePath);
            tackVideo.setRecorderListener(this);
            tackVideo.init();
        }else if (enterType == TACK_PHOTO){
            tackVideo = new TackVideo(this, svTackVideo);
            tackVideo.setSavePhotoPath(savePath);
            tackVideo.setRecorderListener(this);
            tackVideo.init();
        }
    }

    private void initView() {
        svPreView = (SurfaceView) findViewById(R.id.sv_preview);
        svTackVideo = (SurfaceView) findViewById(R.id.sv_tack);
//        prePhoto = (ImageView) findViewById(R.id.iv_image);

        flPreView = (FrameLayout) findViewById(R.id.fl_preview);
        flTackVideo = (FrameLayout) findViewById(R.id.fl_tack);
        ivFinish = (ImageView) findViewById(R.id.iv_finish);
        ivDelete = (ImageView) findViewById(R.id.iv_delete);
        ivConfirm = (ImageView) findViewById(R.id.iv_confirm);
        btnRecord = (RecordedButton) findViewById(R.id.btn_record);
        tvCaption = (TextView) findViewById(R.id.tv_caption);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        if (enterType == PREVIEW_VIDEO) {
            svPreView.setVisibility(View.VISIBLE);
            mToolbar.setVisibility(View.VISIBLE);
        } else if (enterType == TACK_VIDEO) {
            svTackVideo.setVisibility(View.VISIBLE);
            flTackVideo.setVisibility(View.VISIBLE);
            tvCaption.setText("长按拍摄");
        }else if (enterType == TACK_PHOTO){
            svTackVideo.setVisibility(View.VISIBLE);
            flTackVideo.setVisibility(View.VISIBLE);
            tvCaption.setText("点击拍照");
        }
    }

    private void initIntent() {
        Intent intent = getIntent();
        enterType = intent.getIntExtra(TYPE, -1);
        if (enterType == -1) {
            throw new NullPointerException("must afferent enter type");
        }
        if (enterType == PREVIEW_VIDEO) {
            previePath = intent.getStringExtra(PREVIEW_PATH);
            if (previePath == null) {
                throw new NullPointerException("must afferent video path");
            }
        } else if (enterType == TACK_VIDEO || enterType == TACK_PHOTO) {
            savePath = intent.getStringExtra(SAVE_PATH);
            if (savePath == null) {
                throw new NullPointerException("must afferent save path");
            }
        }
    }

    @Override
    public void progress(float currenttime) {
        btnRecord.setProgress(currenttime);
    }

    @Override
    public void recordTimeShort() {
        Toast.makeText(this, "您拍摄的视频太短", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void recordSuccess(File file) {
        //播放视频
        PreView preView = new PreView(this, svPreView);
        preView.setVideoPath(file.getAbsolutePath());
        preView.init();
        svPreView.setVisibility(View.VISIBLE);
        svTackVideo.setVisibility(View.GONE);
        switchOperation(flPreView, flTackVideo);
    }

    @Override
    public void onPictureTaken(File file) {
        // 拍摄照片完毕的回掉
        tackVideo.setPhotoFile(file);
//        svTackVideo.setVisibility(View.GONE);
//        prePhoto.setVisibility(View.VISIBLE);
//        prePhoto.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
        switchOperation(flPreView, flTackVideo);
    }


    private void switchOperation(FrameLayout showView, final FrameLayout hideView) {
        showView.clearAnimation();
        hideView.clearAnimation();
        showView.setVisibility(View.VISIBLE);
        TranslateAnimation showAnim = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                0,
                Animation.RELATIVE_TO_SELF,
                0,
                Animation.RELATIVE_TO_SELF,
                1.5f,
                Animation.RELATIVE_TO_SELF,
                0);
        showAnim.setDuration(500);
        showAnim.setFillAfter(true);
        showAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                hideView.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        TranslateAnimation hideAnim = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                0,
                Animation.RELATIVE_TO_SELF,
                0,
                Animation.RELATIVE_TO_SELF,
                0f,
                Animation.RELATIVE_TO_SELF,
                1.5f
        );
        hideAnim.setDuration(500);
        showAnim.setFillAfter(true);
        showView.setAnimation(showAnim);
        hideView.setAnimation(hideAnim);
    }

    private void closeActivityAnim(){

    }
}
